// pages/product/product.js

import { Product } from '../product/product-model.js';
import { Cart } from '../cart/cart-model.js';

var product = new Product;
var cart = new Cart;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    countsArray: [1,2,3,4,5,6,7,8,9,10],
    productCount: 1,
    currentTabsIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id;
    this.data.id = id;
    
    this._loadData();
  },

  _loadData:function(){
    product.getDetailInfo(this.data.id, (data) => {
      this.setData({
        cartTotalCount: cart.getCartTotalCounts(),
        product:data
      })
    })
  },

  //商品数量实时选择
  bindPickerChang(event){
    var index = event.detail.value;
    var selectedCount = this.data.countsArray[index];

    this.setData({
      productCount:selectedCount
    });
  },

  //当前选项卡选择
  onTabsItemTap: function(event){
    var index = product.getDataSet(event, 'index');
    this.setData({
      currentTabsIndex: index
    });
  },

  //添加到购物车点击事件
  onAddingToCartTap:function(event){
    this.addToCart();
    var counts = this.data.cartTotalCount + this.data.productCount;
    this.setData({
      cartTotalCount: counts
    });
  },

  //商品的数据组装，并添加到购物车
  addToCart:function(){
    var tempObj = {};
    var keys = [ 'id', 'name', 'main_img_url', 'price'];

    for( var key in this.data.product ){
      if( keys.indexOf(key) >= 0 ){
        tempObj[key] = this.data.product[key];
      }
    }
    cart.add( tempObj, this.data.productCount );
  },

  //跳转到购物车页面-导航
  onCartTap:function(){
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  }

  
})